Skip to content

fix: auto-exit index service after idle timeout - #296

Merged
Johnson-zs merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:agent/bugfix/3ef8e79cd963
Nov 19, 2026
Merged

Johnson-zs merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:agent/bugfix/3ef8e79cd963

Conversation

@Johnson-zs

@Johnson-zs Johnson-zs commented Nov 19, 2026 •

Copy link
Copy Markdown

修复内容

新增 IdleExitManager,在 index 服务空闲达到可配置时间后自动退出进程,减少索引全部关闭后的 CPU 占用。

实现方案

  • 通过 Qt DBus 私有 API qDBusAddSpyHook 注册全局 D-Bus 消息观察回调,每条 D-Bus 消息重置空闲定时器
  • 空闲超时后调用 unregisterIndexServices() + QCoreApplication::quit() 优雅退出
  • 超时时间通过 dconfig idle_exit_timeout_minutes 配置(默认 10 分钟,设为 0 禁用自动退出)
  • 服务是 D-Bus 激活的,退出后下次 D-Bus 请求会自动重启进程
  • dde-file-manager 的 keepBackendAlive 在索引开启时每 5 分钟轮询 IsEnabled,会重置定时器保持服务存活

改动文件

  • assets/org.deepin.anything.json — 新增 idle_exit_timeout_minutes dconfig 键
  • src/index/idleexitmanager.h — IdleExitManager 接口声明
  • src/index/idleexitmanager.cpp — 实现:dconfig 读取超时、D-Bus spy hook、空闲定时器
  • src/index/main.cpp — 在服务启动后调用 startIdleExitManager()
  • src/index/CMakeLists.txt — 添加新源文件
  • .gitignore — 排除 .pms/

PMS: TASK-395529

Summary by Sourcery

Automatically stop the index service after configurable inactivity to reduce resource usage while retaining on-demand D-Bus activation.

New Features:

  • Add configurable automatic shutdown for the index service after a period of D-Bus inactivity, with automatic restart on subsequent activation.

Enhancements:

  • Allow idle shutdown to be disabled through configuration and preserve service availability through periodic D-Bus keepalive requests.

Chores:

  • Add the idle-exit manager to the index service build and ignore generated PMS files.

1. Root cause: deepin-anything-index process stays alive even after
   all indexes are disabled, consuming CPU via LoadMonitor timers and
   VFS event processing with no useful work
2. Fix: add IdleExitManager that quits the process after a configurable
   idle period (dconfig idle_exit_timeout_minutes, default 10 min);
   D-Bus spy hook resets timer on activity, D-Bus activation restarts
   on next request
3. Impact: service auto-exits when idle, reducing CPU usage; timeout
   configurable via dconfig (0 disables auto-exit)

Log: index service auto-exits when idle to reduce CPU usage

Influence:
1. Verify service exits after idle timeout with all indexes disabled
2. Verify service restarts on next D-Bus request after auto-exit
3. Verify dconfig idle_exit_timeout_minutes controls the timeout value
4. Verify setting timeout to 0 disables auto-exit

fix: 索引服务空闲超时后自动退出

1. 根因:所有索引关闭后 deepin-anything-index 进程仍存活,
   LoadMonitor 定时器和 VFS 事件处理继续消耗 CPU 但无实际工作
2. 方案:新增 IdleExitManager,进程空闲达到可配置时间后自动退出
   (dconfig idle_exit_timeout_minutes,默认 10 分钟);D-Bus spy
   hook 在有活动时重置计时器,D-Bus 激活机制在下次请求时自动重启
3. 影响:空闲时自动退出降低 CPU 占用;超时时间可通过 dconfig 配置
   (0 表示永不退出)

Log: 索引服务空闲后自动退出,减少 CPU 占用

Influence:
1. 测试所有索引关闭后服务在空闲超时后退出
2. 测试服务退出后下次 D-Bus 请求能自动重启
3. 测试 dconfig idle_exit_timeout_minutes 配置项控制超时时间
4. 测试超时设为 0 时禁用自动退出

PMS: BUG-TASK-395529
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Johnson-zs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@github-actions

Copy link
Copy Markdown
  • 检测到敏感词export变动
详情
    {
    "export": {
        "src/index/idleexitmanager.cpp": {
            "b": [
                "// qDBusAddSpyHook is a Qt DBus internal function exported from libQt6DBus.",
                "// that libQt6DBus exports.  Using extern \"C\" would search for the"
            ]
        }
    }
}

@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026

Copy link
Copy Markdown

Reviewer's Guide

Uses of the API

Wire the idle-exit manager into index-service startup so it begins monitoring once the service has initialized.

  • src/index/main.cpp L6, L136-143

Implementation

Define and implement the idle-exit manager, including its timeout configuration lookup, D-Bus activity hook, and graceful shutdown behavior.

  • src/index/idleexitmanager.cpp L1-84
  • src/index/idleexitmanager.h L1-30

Configuration

Add the dconfig setting that controls the idle-exit timeout and its default.

  • assets/org.deepin.anything.json L6-14, L21-25, L138-148 (+6 small edits)

Register the new idle-exit implementation in the index build.

  • src/index/CMakeLists.txt L70

Ignore the local PMS directory.

  • .gitignore L106

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/index/idleexitmanager.cpp" line_range="76" />
<code_context>
+        qInfo() << "deepin-anything-index: idle timeout reached,"
+                   "exiting to release resources (D-Bus activation will"
+                   "restart on next request)";
+        unregisterIndexServices();
+        QCoreApplication::quit();
+    });
</code_context>
<issue_to_address>
**Active indexing work is interrupted**

When an indexing task runs longer than the configured timeout without D-Bus activity, `unregisterIndexServices()` runs cleanup, which stops the task and marks unfinished work dirty, so indexing is aborted and needs recovery on the next startup.

Defer the idle exit while indexing work is active.
</issue_to_address>

### Comment 2
<location path="src/index/idleexitmanager.cpp" line_range="76" />
<code_context>
+        qInfo() << "deepin-anything-index: idle timeout reached,"
+                   "exiting to release resources (D-Bus activation will"
+                   "restart on next request)";
+        unregisterIndexServices();
+        QCoreApplication::quit();
+    });
</code_context>
<issue_to_address>
**OCR and filename requests fail after exit**

When the process has exited and the next request targets only the OCR or filename service, the installed D-Bus activation entry names only TextIndex, so a request to the OCR or filename service cannot activate the process and fails with a missing-service error.

Add D-Bus activation entries for the OCR and filename service names, or otherwise ensure requests to those names activate the process.

Also at `src/index/idleexitmanager.cpp:77`, `src/index/idleexitmanager.h:20`, `src/index/main.cpp:139`.
</issue_to_address>

### Comment 3
<location path="src/index/idleexitmanager.cpp" line_range="76-78" />
<code_context>
+        qInfo() << "deepin-anything-index: idle timeout reached,"
+                   "exiting to release resources (D-Bus activation will"
+                   "restart on next request)";
+        unregisterIndexServices();
+        QCoreApplication::quit();
+    });
+
+    qDBusAddSpyHook(idleSpyHook);
</code_context>
<issue_to_address>
**Missed changes leave index stale**

When filesystem changes occur while monitoring is enabled but no D-Bus activity reaches the service for the configured timeout, `unregisterIndexServices()` stops filesystem monitoring, and a normal cleanup with no unfinished task leaves the index marked clean. On restart, `handleSilentStart()` skips the global update for a clean index, so files changed while the service was stopped are absent or stale in search results.

Before an idle exit, persist a dirty/recovery state whenever monitoring was enabled so the next activation reconciles changes missed during downtime.
</issue_to_address>

### Comment 4
<location path="src/index/idleexitmanager.cpp" line_range="70" />
<code_context>
+
+    g_idleTimer = new QTimer;
+    g_idleTimer->setSingleShot(true);
+    g_idleTimer->setInterval(timeoutMinutes * 60 * 1000);
+
+    QObject::connect(g_idleTimer, &QTimer::timeout, []() {
</code_context>
<issue_to_address>
**Configured idle timeout is not honored**

When `idle_exit_timeout_minutes` is configured above 35,791, the signed `timeoutMinutes * 60 * 1000` calculation overflows before `QTimer::setInterval()` receives it, so the timer uses an unintended interval and the service exits at the wrong time or fails to time out as configured.

Calculate the interval without signed-integer overflow and handle values outside the timer's supported range.

Also at `src/index/idleexitmanager.cpp:71`.
</issue_to_address>

### Comment 5
<location path="src/index/idleexitmanager.cpp" line_range="50" />
<code_context>
+                                   QString::fromLatin1(kAnythingSchema)));
+    if (dconfig && dconfig->isValid()) {
+        timeoutMinutes = dconfig->value(QString::fromLatin1(kIdleExitTimeoutKey),
+                                        kDefaultIdleExitTimeoutMinutes).toInt();
+        if (timeoutMinutes < 0) {
+            qWarning() << "deepin-anything-index: invalid idle_exit_timeout_minutes"
</code_context>
<issue_to_address>
**Malformed setting disables auto-exit**

When the dconfig value is present but cannot be converted to an integer, a non-numeric configured value makes `toInt()` return 0, which the following check treats as the explicit “disable auto-exit” setting. The service then stays running indefinitely instead of using the default timeout, with no warning about the invalid value.

Check conversion success and use the default timeout with a warning when the value is invalid.
</issue_to_address>

### Comment 6
<location path="src/index/idleexitmanager.cpp" line_range="38" />
<code_context>
+static void idleSpyHook(const QDBusMessage &)
+{
+    if (g_idleTimer)
+        g_idleTimer->start();
+}
+
</code_context>
<issue_to_address>
**Activity from worker threads is missed**

When a D-Bus message is sent from a thread other than the one that owns `g_idleTimer`, `idleSpyHook` calls `QTimer::start()` directly even though the hook runs synchronously for D-Bus messages and can be invoked by a thread sending a message; starting a main-thread timer from that thread is unsafe and does not reliably reset the timeout, so the service can exit despite D-Bus activity.

Marshal the timer reset to the timer's owning thread, for example by queuing a slot or invocation on the timer.
</issue_to_address>

### Comment 7
<location path="src/index/idleexitmanager.cpp" line_range="76" />
<code_context>
+        qInfo() << "deepin-anything-index: idle timeout reached,"
+                   "exiting to release resources (D-Bus activation will"
+                   "restart on next request)";
+        unregisterIndexServices();
+        QCoreApplication::quit();
+    });
</code_context>
<issue_to_address>
**Idle shutdown appears as backend failure**

When the idle timer expires while dde-file-manager is watching the index service, the service unregisters its names on a normal idle exit, so dde-file-manager’s service watcher treats the shutdown as an index-backend failure and switches the UI to an error state instead of treating the service as available for on-demand activation.

Make the client recover cleanly from intentional idle unregistration, or change the shutdown/availability signaling so idle exit is not reported as a backend failure.
</issue_to_address>

### Comment 8
<location path="src/index/idleexitmanager.cpp" line_range="77" />
<code_context>
+                   "exiting to release resources (D-Bus activation will"
+                   "restart on next request)";
+        unregisterIndexServices();
+        QCoreApplication::quit();
+    });
+
</code_context>
<issue_to_address>
**TextIndex activation cannot relaunch binary**

When the process has auto-exited and a caller next requests the TextIndex service, after this code quits the process, a TextIndex request asks D-Bus to activate `/usr/bin/deepin-anything-index`, but the package installs the executable under `/usr/libexec/deepin/deepin-anything-index`. Activation fails, leaving the index service unavailable.

Change the D-Bus activation executable path to the installed libexec path, or install the executable at the path named by `Exec`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

qInfo() << "deepin-anything-index: idle timeout reached,"
"exiting to release resources (D-Bus activation will"
"restart on next request)";
unregisterIndexServices();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Active indexing work is interrupted

When an indexing task runs longer than the configured timeout without D-Bus activity, unregisterIndexServices() runs cleanup, which stops the task and marks unfinished work dirty, so indexing is aborted and needs recovery on the next startup.

Defer the idle exit while indexing work is active.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 76:

**Active indexing work is interrupted**

When an indexing task runs longer than the configured timeout without D-Bus activity, `unregisterIndexServices()` runs cleanup, which stops the task and marks unfinished work dirty, so indexing is aborted and needs recovery on the next startup.

Defer the idle exit while indexing work is active.

qInfo() << "deepin-anything-index: idle timeout reached,"
"exiting to release resources (D-Bus activation will"
"restart on next request)";
unregisterIndexServices();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · OCR and filename requests fail after exit

When the process has exited and the next request targets only the OCR or filename service, the installed D-Bus activation entry names only TextIndex, so a request to the OCR or filename service cannot activate the process and fails with a missing-service error.

Add D-Bus activation entries for the OCR and filename service names, or otherwise ensure requests to those names activate the process.

Also at src/index/idleexitmanager.cpp:77, src/index/idleexitmanager.h:20, src/index/main.cpp:139.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 76:

**OCR and filename requests fail after exit**

When the process has exited and the next request targets only the OCR or filename service, the installed D-Bus activation entry names only TextIndex, so a request to the OCR or filename service cannot activate the process and fails with a missing-service error.

Add D-Bus activation entries for the OCR and filename service names, or otherwise ensure requests to those names activate the process.

Also at `src/index/idleexitmanager.cpp:77`, `src/index/idleexitmanager.h:20`, `src/index/main.cpp:139`.

Comment on lines +76 to +78
unregisterIndexServices();
QCoreApplication::quit();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Missed changes leave index stale

When filesystem changes occur while monitoring is enabled but no D-Bus activity reaches the service for the configured timeout, unregisterIndexServices() stops filesystem monitoring, and a normal cleanup with no unfinished task leaves the index marked clean. On restart, handleSilentStart() skips the global update for a clean index, so files changed while the service was stopped are absent or stale in search results.

Before an idle exit, persist a dirty/recovery state whenever monitoring was enabled so the next activation reconciles changes missed during downtime.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at lines 76-78:

**Missed changes leave index stale**

When filesystem changes occur while monitoring is enabled but no D-Bus activity reaches the service for the configured timeout, `unregisterIndexServices()` stops filesystem monitoring, and a normal cleanup with no unfinished task leaves the index marked clean. On restart, `handleSilentStart()` skips the global update for a clean index, so files changed while the service was stopped are absent or stale in search results.

Before an idle exit, persist a dirty/recovery state whenever monitoring was enabled so the next activation reconciles changes missed during downtime.


g_idleTimer = new QTimer;
g_idleTimer->setSingleShot(true);
g_idleTimer->setInterval(timeoutMinutes * 60 * 1000);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Configured idle timeout is not honored

When idle_exit_timeout_minutes is configured above 35,791, the signed timeoutMinutes * 60 * 1000 calculation overflows before QTimer::setInterval() receives it, so the timer uses an unintended interval and the service exits at the wrong time or fails to time out as configured.

Calculate the interval without signed-integer overflow and handle values outside the timer's supported range.

Also at src/index/idleexitmanager.cpp:71.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 70:

**Configured idle timeout is not honored**

When `idle_exit_timeout_minutes` is configured above 35,791, the signed `timeoutMinutes * 60 * 1000` calculation overflows before `QTimer::setInterval()` receives it, so the timer uses an unintended interval and the service exits at the wrong time or fails to time out as configured.

Calculate the interval without signed-integer overflow and handle values outside the timer's supported range.

Also at `src/index/idleexitmanager.cpp:71`.

QString::fromLatin1(kAnythingSchema)));
if (dconfig && dconfig->isValid()) {
timeoutMinutes = dconfig->value(QString::fromLatin1(kIdleExitTimeoutKey),
kDefaultIdleExitTimeoutMinutes).toInt();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Malformed setting disables auto-exit

When the dconfig value is present but cannot be converted to an integer, a non-numeric configured value makes toInt() return 0, which the following check treats as the explicit “disable auto-exit” setting. The service then stays running indefinitely instead of using the default timeout, with no warning about the invalid value.

Check conversion success and use the default timeout with a warning when the value is invalid.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 50:

**Malformed setting disables auto-exit**

When the dconfig value is present but cannot be converted to an integer, a non-numeric configured value makes `toInt()` return 0, which the following check treats as the explicit “disable auto-exit” setting. The service then stays running indefinitely instead of using the default timeout, with no warning about the invalid value.

Check conversion success and use the default timeout with a warning when the value is invalid.

static void idleSpyHook(const QDBusMessage &)
{
if (g_idleTimer)
g_idleTimer->start();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Activity from worker threads is missed

When a D-Bus message is sent from a thread other than the one that owns g_idleTimer, idleSpyHook calls QTimer::start() directly even though the hook runs synchronously for D-Bus messages and can be invoked by a thread sending a message; starting a main-thread timer from that thread is unsafe and does not reliably reset the timeout, so the service can exit despite D-Bus activity.

Marshal the timer reset to the timer's owning thread, for example by queuing a slot or invocation on the timer.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 38:

**Activity from worker threads is missed**

When a D-Bus message is sent from a thread other than the one that owns `g_idleTimer`, `idleSpyHook` calls `QTimer::start()` directly even though the hook runs synchronously for D-Bus messages and can be invoked by a thread sending a message; starting a main-thread timer from that thread is unsafe and does not reliably reset the timeout, so the service can exit despite D-Bus activity.

Marshal the timer reset to the timer's owning thread, for example by queuing a slot or invocation on the timer.

qInfo() << "deepin-anything-index: idle timeout reached,"
"exiting to release resources (D-Bus activation will"
"restart on next request)";
unregisterIndexServices();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Idle shutdown appears as backend failure

When the idle timer expires while dde-file-manager is watching the index service, the service unregisters its names on a normal idle exit, so dde-file-manager’s service watcher treats the shutdown as an index-backend failure and switches the UI to an error state instead of treating the service as available for on-demand activation.

Make the client recover cleanly from intentional idle unregistration, or change the shutdown/availability signaling so idle exit is not reported as a backend failure.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 76:

**Idle shutdown appears as backend failure**

When the idle timer expires while dde-file-manager is watching the index service, the service unregisters its names on a normal idle exit, so dde-file-manager’s service watcher treats the shutdown as an index-backend failure and switches the UI to an error state instead of treating the service as available for on-demand activation.

Make the client recover cleanly from intentional idle unregistration, or change the shutdown/availability signaling so idle exit is not reported as a backend failure.

"exiting to release resources (D-Bus activation will"
"restart on next request)";
unregisterIndexServices();
QCoreApplication::quit();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · TextIndex activation cannot relaunch binary

When the process has auto-exited and a caller next requests the TextIndex service, after this code quits the process, a TextIndex request asks D-Bus to activate /usr/bin/deepin-anything-index, but the package installs the executable under /usr/libexec/deepin/deepin-anything-index. Activation fails, leaving the index service unavailable.

Change the D-Bus activation executable path to the installed libexec path, or install the executable at the path named by Exec.

Prompt for AI agents
In `src/index/idleexitmanager.cpp` at line 77:

**TextIndex activation cannot relaunch binary**

When the process has auto-exited and a caller next requests the TextIndex service, after this code quits the process, a TextIndex request asks D-Bus to activate `/usr/bin/deepin-anything-index`, but the package installs the executable under `/usr/libexec/deepin/deepin-anything-index`. Activation fails, leaving the index service unavailable.

Change the D-Bus activation executable path to the installed libexec path, or install the executable at the path named by `Exec`.

@Johnson-zs

Copy link
Copy Markdown
Author

/merge

@deepin-bot

deepin-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

This pr cannot be merged! (status: unstable)

@Johnson-zs
Johnson-zs merged commit 784c6e1 into linuxdeepin:develop/snipe Nov 19, 2026
16 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants